package com.tygz.api.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.auto.base.pojo.Attach;
import com.auto.base.pojo.Channel;
import com.auto.base.pojo.City;
import com.auto.base.pojo.GeneralUser;
import com.auto.base.pojo.Post;
import com.auto.base.pojo.PostComment;
import com.auto.base.pojo.PostFocus;
import com.auto.base.pojo.UserWeixin;
import com.auto.base.service.AccessTokenService;
import com.auto.base.service.AttachService;
import com.auto.base.service.ChannelService;
import com.auto.base.service.CityService;
import com.auto.base.service.GeneralUserService;
import com.auto.base.service.PostCommentService;
import com.auto.base.service.PostFocusService;
import com.auto.base.service.PostService;
import com.auto.base.service.UserWeixinService;
import com.auto.common.BaseController;
import com.auto.util.MyJsonConfig;
import com.auto.util.SystemUtil;
import com.base.cache.memcache.CommonMemcached;
import com.base.common.CommonConstants;
import com.base.common.RequestParameters;
import com.base.pojo.Sign;
import com.base.util.DistanceUtil;
import com.base.util.IValidate;
import com.base.util.JUtil;
import com.base.util.Page;
import com.base.util.SecurityCode;
import com.base.util.SignUtil;
import com.tygz.mapper.TygzMapper;
import com.tygz.service.ApiUserService;
import com.tygz.service.SmsSendService;

@Controller
@RequestMapping("/api/user")
//@Scope("prototype")
public class ApiUserController extends BaseController {

	private final Logger log = LoggerFactory.getLogger(ApiUserController.class);
	@Resource private GeneralUserService generalUserService;
	@Resource private AccessTokenService accessTokenService;
	//@Resource private CommonMemcached commonMemcached;
	@Resource private ApiUserService apiUserService;
	@Resource private SmsSendService smsSendService;
	@Resource private CommonMemcached commonMemcached;
	@Resource private CityService cityService;
	@Resource private ChannelService channelService;
	@Resource private PostFocusService postFocusService;
	@Resource private PostService postService;
	@Resource TygzMapper tygzMapper;
	@Resource private AttachService attachService;
	@Resource private PostCommentService postCommentService;
	@Resource private UserWeixinService  userWeixinService;

	private static final String namespace = "com.tygz.api.controller.ApiUserController";

	/**
	 * 短信验证码
	 * @return
	 * @return 返回类型 json
	 * @throws
	 */
	@RequestMapping(value = "securityCode")
	@ResponseBody
	public Object securityCode(String telphone,@ModelAttribute Sign sign,HttpServletRequest request ) {
		//验证秘钥
		try{
			if(sign.getNoCheck() == 0){
				Assert.notNull(sign.getS(), "秘钥为空!");
				Assert.notNull(sign.getT(), "验证秘钥的时间戳参数为空!");
				sign.setP(telphone);
				if(!SignUtil.checkSignature(sign)){
					return setFail("秘钥不正确!");
				}
			}

			Assert.notNull(telphone, "手机号码为空!");
			String code = SecurityCode.getSecurityCode();
			if(this.smsSendService.send(code, telphone)){
				String codeKey = JUtil.getCacheKey(namespace,"code",telphone);
				this.commonMemcached.set(codeKey, 60*5, code);//存5分钟

				return setSuccess("发送验证码成功", code);
			}else{
				return setFail("发送验证码失败");
			}

		}catch(Exception e){
			e.printStackTrace();
			return setFail("发送验证码异常");
		}

	}


	/**
	 * 用户注册
	 * 
	 * @return
	 * @return 返回类型 json
	 * @throws
	 */
	@RequestMapping(value = "register")
	@ResponseBody
	public Object register(@ModelAttribute GeneralUser user,@ModelAttribute Sign sign,String code,HttpServletRequest request ) {

		if(JUtil.isAllKey(code)){
			//万能钥匙

			if(JUtil.isNULL(user)){
				return setFail("注册用户信息为空!");
			}
			if (JUtil.isNULL(user.getTelphone())) {
				return setFail("手机号不能为空");
			}
			if (JUtil.isNull(user.getPassword())) {
				return setFail("密码不能为空");
			}
			if (!IValidate.isMobile(user.getTelphone().toString())) {
				return setFail("手机号码格式错误");
			}
			if (IValidate.lengthEnough(user.getPassword(), 6)) {
				return setFail("密码不少于六位");
			}


		}else{

			//验证秘钥
			if(JUtil.isNull(sign.getS())){
				return setFail("秘钥为空!");
			}
			if(JUtil.isNull(sign.getT())){
				return setFail("验证秘钥的时间戳参数为空!");
			}
			if(JUtil.isNULL(user)){
				return setFail("注册用户信息为空!");
			}


			if (JUtil.isNULL(user.getTelphone())) {
				return setFail("手机号不能为空");
			}
			if (JUtil.isNull(user.getPassword())) {
				return setFail("密码不能为空");
			}
			if (!IValidate.isMobile(user.getTelphone().toString())) {
				return setFail("手机号码格式错误");
			}
			if (IValidate.lengthEnough(user.getPassword(), 6)) {
				return setFail("密码不少于六位");
			}
			if(JUtil.isNull(code)){
				return setFail("短信验证码为空!");
			}
			String codeKey = JUtil.getCacheKey(namespace,"code",user.getTelphone()),codeCache = this.commonMemcached.get(codeKey);
			if(JUtil.isNull(codeCache)){
				return setFail("短信验证码已过期!");
			}
			if(!code.equals(codeCache)){
				return setFail("短信验证码错误!");
			}

			sign.setP(user.getTelphone()+user.getPassword());
			if(!SignUtil.checkSignature(sign)){
				return setFail("秘钥不正确!");
			}
		}

		try {

			GeneralUser tmp = null;
			Long inviteCode = user.getInvitationCode();
			if(!JUtil.isNULL(inviteCode) && !StringUtils.isEmpty(inviteCode.toString())){

				if (!IValidate.isMobile(inviteCode.toString())) {
					return setFail("邀请码格式错误!");
				}
				if (inviteCode == user.getTelphone()){
					return setFail("邀请码和自己注册号码不能相同!");
				}

				log.info("inviteCode=" + inviteCode);
				tmp = new GeneralUser();
				tmp.setTelphone(inviteCode);
				tmp.setEnabled(CommonConstants.ENABLE);
				int count = this.generalUserService.countGeneralUser(tmp);
				// tmp = this.generalUserService.findGeneralUser(tmp, null);
				if (1!=count){
					return setFail("邀请码不正确!");
				}
				tmp = null;
			}

			tmp = new GeneralUser();
			tmp.setTelphone(user.getTelphone());
			tmp.setEnabled(CommonConstants.ENABLE);
			int count = this.generalUserService.countGeneralUser(tmp);
			if (count>0){
				return setFail("该手机号码已经被注册");
			}
			//user.setPassword(MD5Util.getMD5str(user.getPassword()));
			user.setMoney(0);
			user.setAddTime(new Date().getTime());
			//user.setAge(0);
			//user.setLevel(0);

			this.generalUserService.insertGeneralUser(user);
			String codeKey = JUtil.getCacheKey(namespace,"code",user.getTelphone());
			//查询用户并返回
			tmp = new GeneralUser();
			tmp.setTelphone(user.getTelphone());
			tmp.setEnabled(CommonConstants.ENABLE);
			tmp = this.generalUserService.findGeneralUser(tmp, null);
			if(JUtil.isNULL(tmp)){
				return setFail("注册失败");
			}


			//表示已经登陆成功了
			long nowTime = new Date().getTime();
			tmp.setLoginTime(nowTime);
			user = null;
			Map<String,Object> map = new HashMap<String,Object>();
			this.apiUserService.addCache(map, tmp);
			this.commonMemcached.delete(codeKey);
			//tmp.setId(null);
			return setSuccess("注册成功",map);
		} catch (Exception e1) {
			e1.printStackTrace();
			return setFail("注册异常");
		}
	}


	/**
	 * 重置密码
	 * 
	 * @return
	 * @return 返回类型 json
	 * @throws
	 */
	@RequestMapping(value = "resetPwd")
	@ResponseBody
	public Object resetPwd(@ModelAttribute GeneralUser user,@ModelAttribute Sign sign,String code,HttpServletRequest request ) {

		if(JUtil.isAllKey(code)){
			if(JUtil.isNULL(user)){
				return setFail("用户信息为空!");
			}
			if (JUtil.isNULL(user.getTelphone())) {
				return setFail("手机号不能为空");
			}
			if (!IValidate.isMobile(user.getTelphone().toString())) {
				return setFail("手机号码格式错误");
			}
			if (IValidate.lengthEnough(user.getPassword(), 1)) {
				return setFail("新密码不少于一位");
			}

		}else{
			//验证秘钥
			if(JUtil.isNull(sign.getS())){
				return setFail("秘钥为空!");
			}
			if(JUtil.isNull(sign.getT())){
				return setFail("验证秘钥的时间戳参数为空!");
			}
			if(JUtil.isNULL(user)){
				return setFail("用户信息为空!");
			}

			if (JUtil.isNULL(user.getTelphone())) {
				return setFail("手机号不能为空");
			}

			if (!IValidate.isMobile(user.getTelphone().toString())) {
				return setFail("手机号码格式错误");
			}
			if (IValidate.lengthEnough(user.getPassword(), 1)) {
				return setFail("新密码不少于一位");
			}
			if(JUtil.isNull(code)){
				return setFail("短信验证码为空!");
			}
			String codeKey = JUtil.getCacheKey(namespace,"code",user.getTelphone()),codeCache = this.commonMemcached.get(codeKey);
			if(JUtil.isNull(codeCache)){
				return setFail("短信验证码已过期!");
			}
			if(!code.equals(codeCache)){
				return setFail("短信验证码错误!");
			}

			sign.setP(user.getTelphone()+user.getPassword());
			if(!SignUtil.checkSignature(sign)){
				return setFail("秘钥不正确!");
			}

		}

		try {


			GeneralUser tmp = new GeneralUser();
			tmp.setEnabled(CommonConstants.ENABLE);
			tmp.setTelphone(user.getTelphone());
			tmp = this.generalUserService.findGeneralUser(tmp, null);
			if(JUtil.isNULL(tmp)){
				return setFail("该号码不存在系统!，请先注册!");
			}

			GeneralUser updateGeneralUser = new GeneralUser();
			updateGeneralUser.setEnabled(CommonConstants.ENABLE);
			updateGeneralUser.setId(tmp.getId());
			updateGeneralUser.setTelphone(user.getTelphone());
			//updateGeneralUser.setRegisterTime(tmp.getRegisterTime());
			updateGeneralUser.setPassword(user.getPassword());
			this.generalUserService.modifyGeneralUserByPkSelective(updateGeneralUser);
			String key = JUtil.getCacheKey("com.ajw.service.impl.ApiUserServiceImpl","access",user.getTelphone());
			this.commonMemcached.delete(key);
			String userKey = JUtil.getCacheKey("com.ajw.service.impl.ApiUserServiceImpl","generalUser",tmp.getId());
			this.commonMemcached.delete(userKey);
			String codeKey = JUtil.getCacheKey(namespace,"code",user.getTelphone());
			this.commonMemcached.delete(codeKey);

			return setSuccess("重置成功");
		} catch (Exception e1) {
			e1.printStackTrace();
			return setFail("重置异常");
		}
	}
	
	/**
	 * 微信用户登陆
	 * 
	 * @return
	 * @return 返回类型 json
	 * @throws
	 */
	@RequestMapping(value = "weilogin")
	@ResponseBody
	public Object weilogin(String openId,String accessToken,@ModelAttribute Sign sign, HttpServletRequest request ) {
		//验证秘钥
		if(sign.getNoCheck() == 0){
			if(sign.getNoCheck() == 0){
				if(JUtil.isNull(sign.getS())){
					return setFail("秘钥为空!");
				}
				if(JUtil.isNull(sign.getT())){
					return setFail("验证秘钥的时间戳参数为空!");
				}
			}
			if(!SignUtil.checkSignature(sign)){
				return setFail("秘钥不正确!");
			}
		}

		try {
			GeneralUser user =  apiUserService.weixinLogin(openId,accessToken);
			return setSuccess("登陆成功！", user);
		} catch (Exception e1) {
			e1.printStackTrace();
			if(e1 instanceof RuntimeException){
				return setFail(e1.getMessage());
			}
			return setFail("登陆异常");
		}
	}


	/**
	 * 用户登陆
	 * 
	 * @return
	 * @return 返回类型 json
	 * @throws
	 */
	@RequestMapping(value = "login")
	@ResponseBody
	public Object login(@ModelAttribute GeneralUser user,@ModelAttribute Sign sign, HttpServletRequest request ) {
		//验证秘钥
		if(sign.getNoCheck() == 0){
			if(sign.getNoCheck() == 0){
				if(JUtil.isNull(sign.getS())){
					return setFail("秘钥为空!");
				}
				if(JUtil.isNull(sign.getT())){
					return setFail("验证秘钥的时间戳参数为空!");
				}
			}
			sign.setP(user.getTelphone()+user.getPassword());
			if(!SignUtil.checkSignature(sign)){
				return setFail("秘钥不正确!");
			}
		}


		if(JUtil.isNULL(user)){
			return setFail("用户信息为空!");
		}
		//		if(JUtil.isNull(code)){
		//			return setFail("短信验证码为空!");
		//		}
		if (JUtil.isNULL(user.getTelphone())) {
			return setFail("手机号不能为空");
		}
		if (JUtil.isNull(user.getPassword())) {
			return setFail("密码不能为空");
		}
		if (!IValidate.isMobile(user.getTelphone().toString())) {
			return setFail("手机号码格式错误");
		}
		if (IValidate.lengthEnough(user.getPassword(), 6)) {
			return setFail("密码不少于六位");
		}
//		if(JUtil.isNULL(user.getLng())){
//			return setFail("经度为空");
//		}
//		if(JUtil.isNULL(user.getLat())){
//			return setFail("纬度为空");
//		}
		//		String codeKey = JUtil.getCacheKey(namespace,"code",user.getTelphone()),codeCache = this.commonMemcached.get(codeKey);
		//		if(JUtil.isNull(codeCache)){
		//			return setFail("短信验证码已过期!");
		//		}
		//		if(!code.equals(codeCache)){
		//			return setFail("短信验证码错误!");
		//		}



		try {
			Map<String,Object> map = new HashMap<String,Object>();
			apiUserService.login(map, user);

			return setSuccess("登陆成功！", map);
		} catch (Exception e1) {
			e1.printStackTrace();
			if(e1 instanceof RuntimeException){
				return setFail(e1.getMessage());
			}
			return setFail("登陆异常");
		}
	}

	/**
	 * 获取城市列表
	 * 
	 * @return 返回类型 json
	 * @throws
	 */
	@RequestMapping(value = "getCity")
	@ResponseBody
	public Object getCity(@ModelAttribute Sign sign, HttpServletRequest request){
		//验证秘钥
		if(sign.getNoCheck() == 0){
			if(JUtil.isNull(sign.getS())){
				return setFail("秘钥为空!");
			}
			if(JUtil.isNull(sign.getT())){
				return setFail("验证秘钥的时间戳参数为空!");
			}
			if(!SignUtil.checkSignature(sign)){
				return setFail("秘钥不正确!");
			}
		}

		City record = new City();
		record.setEnabled(CommonConstants.ENABLE);
		record.setCityType(2);//第二级表示城市
		try {
			List<City> list = this.cityService.listCity(record,null, null, null);
			if(null == list){
				return setSuccess("获取城市列表成功", new ArrayList());
			}
			return setSuccess("获取城市列表成功", list);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return setFail("获取城市列表失败!");
		}
	}

	/**
	 * 获取用户信息
	 * 
	 * @return
	 * @return 返回类型 json
	 * @throws
	 */
	@RequestMapping(value = "getUserInfo")
	@ResponseBody
	public Object getUserInfo(Integer userId,@ModelAttribute Sign sign, HttpServletRequest request ) {
		//必要信息
		if (JUtil.isNULL(userId)) {
			return setFail("用户ID不能为空");
		}

		//验证秘钥
		if(sign.getNoCheck() == 0){
			if(JUtil.isNull(sign.getS())){
				return setFail("秘钥为空!");
			}

			if(JUtil.isNull(sign.getT())){
				return setFail("验证秘钥的时间戳参数为空!");
			}

			if(!SignUtil.checkSignature(sign)){
				return setFail("秘钥不正确!");
			}
		}
		try {
			GeneralUser user = this.apiUserService.getUserById(userId);
			//JSONObject jsonobj = JSONObject.fromObject(user,MyJsonConfig.JSON_CFG);
			//jsonobj.remove("id");
			return setSuccess("获取用户信息成功！", user);
		} catch (Exception e1) {
			e1.printStackTrace();
			if(e1 instanceof RuntimeException || e1 instanceof IllegalArgumentException){
				return setFail(e1.getMessage());
			}
			return setFail("获取用户信息异常");
		}
	}

	/**
	 * 修改用户信息
	 * 
	 * @return
	 * @return 返回类型 json
	 * @throws
	 */
	@RequestMapping(value = "updateUserInfo")
	@ResponseBody
	public Object updateUserInfo(@ModelAttribute GeneralUser user,@ModelAttribute Sign sign, HttpServletRequest request ) {
		//必要信息
		if (JUtil.isNULL(user)) {
			return setFail("用户信息不能为空");
		}
		if (JUtil.isNULL(user.getId())) {
			return setFail("用户ID不能为空");
		}

		//验证秘钥
		if(sign.getNoCheck() == 0){
			if(JUtil.isNull(sign.getS())){
				return setFail("秘钥为空!");
			}

			if(JUtil.isNull(sign.getT())){
				return setFail("验证秘钥的时间戳参数为空!");
			}

			if(!SignUtil.checkSignature(sign)){
				return setFail("秘钥不正确!");
			}
		}
		try {
			GeneralUser query = this.apiUserService.updateUserInfo(user);
			return setSuccess("修改成功！", query);
		} catch (Exception e1) {
			e1.printStackTrace();
			if(e1 instanceof RuntimeException || e1 instanceof IllegalArgumentException){
				return setFail(e1.getMessage());
			}
			return setFail("修改异常");
		}
	}

	/**
	 * 获取频道信息
	 * 
	 * @return
	 * @return 返回类型 json
	 * @throws
	 */
	@RequestMapping(value = "getTopic")
	@ResponseBody
	public Object getTopic(Integer type,@ModelAttribute Sign sign, HttpServletRequest request ) {
		//必要信息

		//验证秘钥
		if(sign.getNoCheck() == 0){
			if(JUtil.isNull(sign.getS())){
				return setFail("秘钥为空!");
			}

			if(JUtil.isNull(sign.getT())){
				return setFail("验证秘钥的时间戳参数为空!");
			}

			if(!SignUtil.checkSignature(sign)){
				return setFail("秘钥不正确!");
			}
		}
		try {

			Channel tmp = new Channel();
			if(null!=type){
				tmp.setIsHot(type);
			}
			tmp.setEnabled(CommonConstants.ENABLE);
			List<Channel> list = this.channelService.listChannel(tmp, null, null, null);
			if(null == list){
				return setSuccess("获取成功", new ArrayList());
			}
			return setSuccess("获取成功", list);
		} catch (Exception e1) {
			e1.printStackTrace();
			if(e1 instanceof RuntimeException || e1 instanceof IllegalArgumentException){
				return setFail(e1.getMessage());
			}
			return setFail("获取信息异常");
		}
	}

	/**
	 * 赞帖子
	 * 
	 * @return
	 * @return 返回类型 json
	 * @throws
	 */
	@RequestMapping(value = "doAgree")
	@ResponseBody
	public Object doAgree(@ModelAttribute PostFocus postFocus,@ModelAttribute Sign sign, HttpServletRequest request ) {
		//必要信息
		if (JUtil.isNULL(postFocus)) {
			return setFail("被赞信息不能为空");
		}
		if (JUtil.isNULL(postFocus.getUid())) {
			return setFail("赞人者ID不能为空");
		}
		if (JUtil.isNULL(postFocus.getPostId())) {
			return setFail("帖子ID不能为空");
		}

		//验证秘钥
		if(sign.getNoCheck() == 0){
			if(JUtil.isNull(sign.getS())){
				return setFail("秘钥为空!");
			}

			if(JUtil.isNull(sign.getT())){
				return setFail("验证秘钥的时间戳参数为空!");
			}

			if(!SignUtil.checkSignature(sign)){
				return setFail("秘钥不正确!");
			}
		}
		try {

			int count = this.apiUserService.doAgree(postFocus);
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("count", count);
			return setSuccess("操作成功！", map);
		} catch (Exception e1) {
			e1.printStackTrace();
			if(e1 instanceof RuntimeException || e1 instanceof IllegalArgumentException){
				return setFail(e1.getMessage());
			}
			return setFail("操作异常");
		}
	}


	/**
	 * 发帖子
	 * 
	 * @return
	 * @return 返回类型 json
	 * @throws
	 */
	@RequestMapping(value = "doPublish")
	@ResponseBody
	public Object doPublish(@ModelAttribute Post post, String  fileIds,@ModelAttribute Sign sign, HttpServletRequest request ) {
		//必要信息
		if (JUtil.isNULL(post)) {
			return setFail("帖子信息不能为空");
		}
		if (JUtil.isNull(post.getContent()) && JUtil.isNull(fileIds)) {
			return setFail("帖子内容和图片不能都为空！");
		}
		if(JUtil.isNULL(post.getAddUserId())){
			return setFail("发帖人ID不能都为空！");
		}


		//验证秘钥
		if(sign.getNoCheck() == 0){
			if(JUtil.isNull(sign.getS())){
				return setFail("秘钥为空!");
			}

			if(JUtil.isNull(sign.getT())){
				return setFail("验证秘钥的时间戳参数为空!");
			}

			if(!SignUtil.checkSignature(sign)){
				return setFail("秘钥不正确!");
			}
		}
		try {

			this.apiUserService.doPush(post,fileIds);
			return setSuccess("发帖成功！");
		} catch (Exception e1) {
			e1.printStackTrace();
			if(e1 instanceof RuntimeException || e1 instanceof IllegalArgumentException){
				return setFail(e1.getMessage());
			}
			return setFail("发帖异常");
		}
	}

	/**
	 * 附件上传
	 */
	@RequestMapping(value = "UploadfileBak")
	@ResponseBody
	public Object UploadfileBak(int  type,@ModelAttribute Sign sign, HttpServletRequest request) {


		DefaultMultipartHttpServletRequest req = (DefaultMultipartHttpServletRequest) request;       
		try {
			request.setCharacterEncoding("UTF-8");
			Map<String, MultipartFile> files = req.getFileMap();  
			if(null == files || files.isEmpty() ){
				return setFail("上传文件为空!");
			}
			if(type<1 || type>3){
				return setFail("type值范围有误");
			}
			//验证秘钥
			if(sign.getNoCheck() == 0){
				if(JUtil.isNull(sign.getS())){
					return setFail("秘钥为空!");
				}

				if(JUtil.isNull(sign.getT())){
					return setFail("验证秘钥的时间戳参数为空!");
				}

				if(!SignUtil.checkSignature(sign)){
					return setFail("秘钥不正确!");
				}
			}

			List<MultipartFile> list = new ArrayList<MultipartFile>();

			for (String key : files.keySet()) {                         
				MultipartFile file = files.get(key);  
				list.add(file);
				//				System.out.println(file.getName());                       
				//				System.out.println(file.getSize());  
				//				String oldFileName = file.getOriginalFilename(), suffix = JUtil.getFileSuffix(oldFileName);
				//				String filePathPreffix = SystemUtil.getInstance().getParamMap().get("sys_file_save_dir");
				//				String realPath = filePathPreffix+"/"+type;
				//				String newFileName =JUtil.getFileNameByParameters(""+type,suffix);
				//				FileOutputStream fileOutput = null;                         
				//				try {                                
				//					fileOutput = new FileOutputStream(realPath+"/"+newFileName);                             
				//					fileOutput.write(file.getBytes());                                 
				//					fileOutput.flush();                                 
				//					fileOutput.close();       
				//					
				//				} catch (FileNotFoundException e) {       
				//					e.printStackTrace();                        
				//				} catch (IOException e) {   
				//					e.printStackTrace();                      
				//				}                
			}        

			JSONArray arr = this.apiUserService.upload((MultipartFile[])list.toArray(), type);
			//Map<String,String> map = new HashMap<String,String>();
			//map.put("fileIds", JUtil.splitListIntToString(rtnList));
			return setSuccess("上传成功", arr);

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();

			if(e instanceof RuntimeException || e instanceof IllegalArgumentException){
				return setFail(e.getMessage());
			}
			return setFail("上传异常");
		}               

	}


	/**
	 * 附件上传
	 */
	@RequestMapping(value = "Uploadfile")
	@ResponseBody
	public Object Uploadfile(@RequestParam MultipartFile[] uploadFiles, int  type,@ModelAttribute Sign sign, HttpServletRequest request) {
		if(null == uploadFiles || uploadFiles.length == 0 ){
			return setFail("上传文件为空!");
		}
		//验证秘钥
		if(sign.getNoCheck() == 0){
			if(JUtil.isNull(sign.getS())){
				return setFail("秘钥为空!");
			}

			if(JUtil.isNull(sign.getT())){
				return setFail("验证秘钥的时间戳参数为空!");
			}

			if(!SignUtil.checkSignature(sign)){
				return setFail("秘钥不正确!");
			}
		}
		try {
			JSONArray arr = this.apiUserService.upload(uploadFiles, type);
			//Map<String,String> map = new HashMap<String,String>();
			//map.put("fileIds", JUtil.splitListIntToString(list));
			return setSuccess("上传成功", arr);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			if(e1 instanceof RuntimeException || e1 instanceof IllegalArgumentException){
				return setFail(e1.getMessage());
			}
			return setFail("上传异常");
		}
	}

	/**
	 * 附近的老乡
	 */
	@RequestMapping(value = "lbsPeople")
	@ResponseBody
	public Object lbsPeople(@ModelAttribute RequestParameters requestParameters,@ModelAttribute Sign sign,HttpServletRequest request){
		Map<String,Object> queryMap = requestParameters.getQueryProxy();
		double distance = 50000;
		if(queryMap.containsKey("distance") && null != queryMap.get("distance")){
			distance = Double.parseDouble(queryMap.get("distance").toString());
			queryMap.remove("distance");
		}

		if(!queryMap.containsKey("lat") || null == queryMap.get("lat")){
			return setFail("lat不能为空!");
		}
		double lat = Double.parseDouble(queryMap.get("lat").toString());
		queryMap.remove("lat");
		if(!queryMap.containsKey("lng") || null == queryMap.get("lng")){
			return setFail("lng不能为空!");
		}
		double lng = Double.parseDouble(queryMap.get("lng").toString());
		queryMap.remove("lng");
		Page paging = null;
		if(1 != requestParameters.getIsNonPage()){
			//不分页
			int page = requestParameters.getPage(), rows = requestParameters.getRows();
			if(0 >= page){
				page = 1;
			}
			if(0>=rows){
				rows = 10;
			}
			paging = Page.getInstance(page-1,rows);

		}
		Map<String, Object> paramsMap = DistanceUtil.getAroundBaseInfoMap(lat, lng, distance);
		paramsMap.put("page", paging);
		//验证秘钥
		if(sign.getNoCheck() == 0){
			if(JUtil.isNull(sign.getS())){
				return setFail("秘钥为空!");
			}

			if(JUtil.isNull(sign.getT())){
				return setFail("验证秘钥的时间戳参数为空!");
			}

			if(!SignUtil.checkSignature(sign)){
				return setFail("秘钥不正确!");
			}
		}

		paramsMap.putAll(queryMap);
		try {
			List<Map<String, Object>> list = this.tygzMapper.selectLx(paramsMap);
			int count = this.tygzMapper.selectLxCount(paramsMap);
			JSONObject json = new JSONObject();
			json.put("rows", list);
			json.put("count", count);
			return setSuccess("获取数据成功", json);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return setFail("获取数据失败");
		}
	}


	/**
	 * 附近的帖子
	 */
	@RequestMapping(value = "lbsDynamic")
	@ResponseBody
	public Object lbsDynamic(@ModelAttribute RequestParameters requestParameters,@ModelAttribute Sign sign, HttpServletRequest request){
		Map<String,Object> queryMap = requestParameters.getQueryProxy();
		double distance = 50000;
		if(queryMap.containsKey("distance") && null != queryMap.get("distance")){
			distance = Double.parseDouble(queryMap.get("distance").toString());
			queryMap.remove("distance");
		}

		if(!queryMap.containsKey("lat") || null == queryMap.get("lat")){
			return setFail("lat不能为空!");
		}
		double lat = Double.parseDouble(queryMap.get("lat").toString());
		queryMap.remove("lat");
		if(!queryMap.containsKey("lng") || null == queryMap.get("lng")){
			return setFail("lng不能为空!");
		}
		double lng = Double.parseDouble(queryMap.get("lng").toString());
		queryMap.remove("lng");

		Page paging = null;
		if(1 != requestParameters.getIsNonPage()){
			//不分页
			int page = requestParameters.getPage(), rows = requestParameters.getRows();
			if(0 >= page){
				page = 1;
			}
			if(0>=rows){
				rows = 10;
			}
			paging = Page.getInstance(page-1,rows);

		}

		Map<String, Object> paramsMap = DistanceUtil.getAroundBaseInfoMap(lat, lng, distance);
		paramsMap.put("page", paging);
		//验证秘钥
		if(sign.getNoCheck() == 0){
			if(JUtil.isNull(sign.getS())){
				return setFail("秘钥为空!");
			}

			if(JUtil.isNull(sign.getT())){
				return setFail("验证秘钥的时间戳参数为空!");
			}

			if(!SignUtil.checkSignature(sign)){
				return setFail("秘钥不正确!");
			}
		}
		paramsMap.putAll(queryMap);
		try {
			List<Map<String, Object>> list = this.tygzMapper.selectTz(paramsMap);

			for(Map<String,Object> map:list){
				java.lang.Long id = (java.lang.Long)map.get("id");
				//获取图片
				Attach tmp = new Attach();
				tmp.setEnabled(CommonConstants.ENABLE);
				tmp.setItemId(id.intValue());
				tmp.setItemType(CommonConstants.SELFTYPE);
				List<Attach> listAttach= this.attachService.listAttach(tmp, null,null, null);
				List<String> urlList = new ArrayList();
				if(null!=listAttach && !listAttach.isEmpty()){
					for(Attach atmp:listAttach){
						String fileName = atmp.getFileName(), url =null;
						if(null != fileName){
							url = SystemUtil.getInstance().getParamMapValue("sys_file_down_url_preffix")+"/"+CommonConstants.SELFTYPE+"/"+ fileName;
						}else{
							url = "";
						}
						urlList.add(url);
					}
				}

				map.put("contentImg", urlList);
				// 获取👍的人
				PostFocus pf = new PostFocus();
				pf.setPostId(id.intValue());
				List<PostFocus> listPostFocus = this.postFocusService.listPostFocus(pf, null, null, null);
				List<Map<String,Object>> agreeUser = new ArrayList<Map<String,Object>>();
				if(null!=listPostFocus && !listPostFocus.isEmpty()){
					int i=0;
					for(PostFocus pp:listPostFocus){
						if(i<5){
							GeneralUser tmpUser = new GeneralUser();
							tmpUser.setEnabled(CommonConstants.ENABLE);
							tmpUser.setId(pp.getUid());
							tmpUser = this.generalUserService.findGeneralUser(tmpUser, null);
							if(null!=tmpUser){

								Map<String,Object> tmpMap = new HashMap<String,Object>();
								tmpMap.put("userName", tmpUser.getUserName());
								tmpMap.put("userIcon", tmpUser.getUserIcon());
								tmpMap.put("level", tmpUser.getLevel());
								//tmpMap.put("age", tmpUser.getAge());
								tmpMap.put("birth", tmpUser.getBirth());
								agreeUser.add(tmpMap);

								i++;
							}
						}

					}

				}
				map.put("agreeUser", agreeUser);

				//获取评论
				PostComment comment = new PostComment();
				comment.setEnabled(CommonConstants.ENABLE);
				comment.setPostId(id.intValue());
				List<Map<String,Object>> commentListMap = new ArrayList<Map<String,Object>>();
				List<PostComment> listPostComment = this.postCommentService.listPostComment(comment, null, null, null);
				if(null!=listPostComment && !listPostComment.isEmpty()){
					for(PostComment c:listPostComment){
						GeneralUser tmpUser = new GeneralUser();
						tmpUser.setEnabled(CommonConstants.ENABLE);
						tmpUser.setId(c.getUserId());
						tmpUser = this.generalUserService.findGeneralUser(tmpUser, null);
						if(null!=tmpUser){
							Map<String,Object> tmpMap = new HashMap<String,Object>();

							tmpMap.put("userName", tmpUser.getUserName());
							tmpMap.put("userIcon", tmpUser.getUserIcon());
							tmpMap.put("sex", tmpUser.getSex());
							tmpMap.put("addTime", c.getAddTime());
							tmpMap.put("content", c.getContent());
							tmpMap.put("cityName", tmpUser.getCityName());
							tmpMap.put("birth", tmpUser.getBirth());
							commentListMap.add(tmpMap);
							
						}
					}
				}
				map.put("comment", commentListMap);
			}

			int count = this.tygzMapper.selectTzCount(paramsMap);
			Map<String,Object> map = new HashMap<String,Object>();
			//JSONObject json = new JSONObject();
			map.put("rows", list);
			map.put("count", count);

			return setSuccess("获取数据成功", map);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return setFail("获取数据失败");
		}

	}
   
	/**
	 * 获取帖子赞用户的列表
	 */
	@RequestMapping(value = "obtainAgreeList")
	@ResponseBody
	public Object obtainAgreeList(Integer postId,@ModelAttribute RequestParameters requestParameters,@ModelAttribute Sign sign,HttpServletRequest request){
		Page paging = null;boolean flag = 1 != requestParameters.getIsNonPage();
		int start = 0,end = 10;
		try{
		if(flag){
			//分页
			int page = requestParameters.getPage(), rows = requestParameters.getRows();
			if(0 >= page){
				page = 1;
			}
			if(0>=rows){
				rows = 10;
			}
			paging = Page.getInstance(page-1,rows);
			//start = page -1;
			//end = start*page;
		}
		
		com.alibaba.fastjson.JSONObject json = this.apiUserService.obtainAgreeList(postId,paging);
			return setSuccess("获取数据成功", json);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return setFail("获取数据失败");
		}

	}

	
	
}